#---------------------------------------------#
# iSpace Grouping                             #
# Date:2020/02/13                             #
# Author:hejing                               #
# Email: hejing@uic.edu.cn  
# update:2023/12/08                           #
#---------------------------------------------#

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time


class Group:
    # chrome_options = Options()
    # driver = webdriver.Chrome(chrome_options=chrome_options)
    driver = webdriver.Chrome()
    url = "https://ispace.uic.edu.cn/login/index.php"
    username = ''
    password = ''
    group_name = []

    def __init__(self, url, username, password, group_name):
        self.url = url
        self.username = username
        self.password = password
        self.group_name = group_name

    def login(self):
        """
        Step1:
            User should login first.

        """
        try:
            self.driver.get(self.url)
            # 睡眠2秒
            time.sleep(2)
            user = self.driver.find_element(By.ID,"username")
            user.send_keys(self.username)
            # 找到密码输入密码
            self.driver.find_element(By.ID,"password").send_keys(self.password)
            # 点击登录按钮实现登录
            # driver.find_element_by_xpath("//button").click()
            self.driver.find_element(By.ID,"loginbtn").click()
            # 登录成功后跳转首页，进行加载，休眠10秒加载页面
            time.sleep(5)
            # drive.switch_to_default_content()
            cookies_list = self.driver.get_cookies()
            print(cookies_list)
        except Exception as e:
            print("出现问题", e)

    def create_groups(self, courseid):
        """
        Step2:
            Create groups.
        """

        for item in self.group_name:
            group_url = f"https://ispace.uic.edu.cn/group/group.php?courseid={courseid}"
            print(group_url)

            self.driver.get(group_url)
            time.sleep(5)
            
            self.driver.find_element(By.ID,"id_name").send_keys(item)
            self.driver.find_element(By.ID,"id_submitbutton").click()

    def add_user_into_group(self, courseid, user_data):
        """
        Step3:
            Put users into groups.
        """
        for i in range(len(user_data)):
            group_url = f"https://ispace.uic.edu.cn/group/index.php?id={courseid}"
            self.driver.get(group_url)
            time.sleep(2)
            groups_select = self.driver.find_element(By.ID,"groups")
            groups = groups_select.find_elements(By.TAG_NAME,"option")

            for item in groups:
                if "(0)" not in item.text:
                    continue
                option_text = item.text.replace(" (0)", "")
                item.click()
                self.driver.find_element(By.ID,"showaddmembersform").click()
                time.sleep(1)

                name_list = user_data[option_text]
                for item in name_list:
                    self.driver.find_element(By.ID,
                        "addselect_searchtext").send_keys(item)
                    time.sleep(1)
                    target = self.driver.find_element(By.ID,
                        "addselect").find_elements(By.TAG_NAME,"option")[0]
                    target.click()
                    time.sleep(1)
                    self.driver.find_element(
                        By.CSS_SELECTOR, "#add").send_keys(Keys.ENTER)
                    time.sleep(1)
                    self.driver.find_element(By.ID,
                        "addselect_clearbutton").click()
                    time.sleep(1)
                break


# get group info from txt
def get_group_data(filename):
    user_group_data = dict()
    with open(filename, "r", encoding='utf-8') as f:
        lines = f.readlines()
        for line in lines:
            data = line.strip("\n").split(",")

            if data[1] in user_group_data.keys():
                user_group_data[data[1]].append(data[0])
            else:
                user_group_data[data[1]] = [data[0]]

    return user_group_data


if __name__ == '__main__':
    # STEP1: update ispace course id
    # UIC course id
    # FIXME: change it to your own course id
    # https://ispace.uic.edu.cn/course/view.php?id=8778

    COURSE_ID = 642

    LOGIN_URL = "https://ispace.uic.edu.cn/login/index.php"  # login url

    # username = 'hejing'  # ispace username
    # USERNAME = input("iSpace username:")
    USERNAME = "hejing"
    # ispace password
    PASSWORD = input("iSpace Password:")

    # get group data
    data_file = f'courseid_{COURSE_ID}_groups_data.txt'

    USER_GROUP_DATA = get_group_data(data_file)

    print(USER_GROUP_DATA)

    # get the company name from group data
    GROUP_NAME = []
    for k in USER_GROUP_DATA.keys():
        GROUP_NAME.append(k)

    print(GROUP_NAME)

    # constructor
    ispace = Group(LOGIN_URL, USERNAME, PASSWORD, GROUP_NAME)
    # step 1
    ispace.login()
    # step 2
    ispace.create_groups(COURSE_ID)
    # step 3
    ispace.add_user_into_group(COURSE_ID, USER_GROUP_DATA)
